package com.bridge.common.http;

import com.bridge.common.base.BaseActivity;
import com.bridge.common.dialog.VDialog;
import com.bridge.common.utils.ToastshowUtils;

import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**`
 * Retrofit Callback基类
 */

abstract public class BaseCallback<T> implements Callback<T> {
    protected boolean isAutoCloseLoadingDialog = true;//自动关闭LoadingDialog
    //WeakReference<BaseActivity> weakReference ;
    public BaseCallback(){}

    /**
     * 是否自动关闭LoadingDialog
     * **/
    public BaseCallback(boolean isAutoCloseLoadingDialog){
        this.isAutoCloseLoadingDialog = isAutoCloseLoadingDialog;
    }

    /**
     * 带进度的：还没来得及测试！演示版本尽量不要通过该构造方法初始化
     * @param activity
     */
    public BaseCallback(BaseActivity activity ){
        this.isAutoCloseLoadingDialog = true;
        //weakReference  = new WeakReference<>(activity);
        VDialog.getInstance().showLoadingDialog("正在加载",activity,true,true);
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if(isAutoCloseLoadingDialog){
            //自动结束加载框
            VDialog.getInstance().hideLoadingDialog();
        }
        if(response.isSuccessful()){
            try {
                onHandleSuccess(response.body());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            onHandleError(response.body());
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        VDialog.getInstance().hideLoadingDialog();
        ToastshowUtils.showToastSafe("网络连接失败");
        onHandleError(null);
    }


    protected abstract void onHandleSuccess(T data) throws IOException;

    protected void onHandleError(T response){
        VDialog.getInstance().hideLoadingDialog();
        ToastshowUtils.showToastSafe("无法连接服务器");
    }
}
